package cn.conac.rc.msg.utils;

import java.util.Date;
import java.util.Map;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.jolokia.util.DateUtil;

import cn.conac.rc.framework.utils.DateUtils;

public class SendSmsUtil {

	private static final Log log = LogFactory.getLog(SendSmsUtil.class);
	private static final String SMS_SEND_UTF8_URL = "http://dx.ipyy.net/sms.aspx?action=send";
	private static final String SMS_SEND_GB2132_URL = "http://dx.ipyy.net/smsGBK.aspx";
	private static final String SMS_SEND_JSON_URL = "http://dx.ipyy.net/smsJson.aspx";
	private static final String SMS_SEND_JSONMD_URL = "http://dx.ipyy.net/ensms.ashx";
	/**
	 * 功能:发送短信 返回是否成功（三小时内只能发送3个）
	 * @author lijian
	 * @since 2016-12-29
	 * @param mobileNumber 电话号码（1个）
	 * @param templateName 模板名称
	 * @param parameter    模板参数
	 * @param jobTime      定时发送时间（可以为空 null）
	 * @return
	 */
	public static int sendSmsJson(String mobileNumber, String templateName, Map<String, String> parameter,Date jobTime){
		String[] mobiles = new String[1];
		mobiles[0]=mobileNumber;
		return sendSmsJson(mobiles, templateName, parameter,jobTime);
	}
	

	/**
	 * 功能:发送短信 返回是否成功（三小时内只能发送3个）
	 * @author lijian
	 * @since 2016-12-29
	 * @param mobileNumber 电话号码（多个）
	 * @param smsContent   短信内容
	 * @param jobTime      定时发送时间（可以为空 null）
	 * @return
	 */
	public static int sendSmsJson(String[] mobileNumber, String smsContent,Date jobTime){
		ResourceBundle smsconfig = PropertyResourceBundle.getBundle("smsconfig");
		smsContent = smsContent+smsconfig.getString("orgName");//内容+【签名】
		System.out.println("::::smsContent=" + smsContent);
		int fret = 0;// 成功
		try {
			String mobiles = "";
			if(mobileNumber==null){
				return 1; // 成功 参数为空
			}
			for(String mobile : mobileNumber){
				log.info("手机号码："+mobile);
				if(StringUtils.isEmpty(mobiles)){
					mobiles+=mobile;
				}else{
					mobiles+=mobile+",";
				}
			}
			System.out.println("user_id=" + smsconfig.getString("user_id"));
			System.out.println("login_id=" + smsconfig.getString("login_id"));
			System.out.println("login_password=" + smsconfig.getString("login_password"));
			HttpClient client=new HttpClient();				
			PostMethod post=new PostMethod(SMS_SEND_UTF8_URL);
			post.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
			NameValuePair userid=new NameValuePair("userid",smsconfig.getString("user_id"));
			NameValuePair account=new NameValuePair("account",smsconfig.getString("login_id"));
			NameValuePair password=new NameValuePair("password",smsconfig.getString("login_password"));
			NameValuePair mobile=new NameValuePair("mobile",mobiles);
			NameValuePair content=new NameValuePair("content",new String(smsContent.getBytes("utf-8"),"utf-8"));
			NameValuePair sendTime=new NameValuePair("sendTime","");
			if(jobTime!=null){
				String sendTimeString = DateUtils.getFormatDateTime(jobTime,DateUtils.PARSE_PATTERNS[1]);
				sendTime=new NameValuePair("sendTime",sendTimeString);
			}
			NameValuePair extno=new NameValuePair("extno","");
			post.setRequestBody(new NameValuePair[]{userid,account,password,mobile,content,sendTime,extno});
			int statu=client.executeMethod(post);
			System.out.println("statu="+statu);
			String str=post.getResponseBodyAsString();
			System.out.println(str);			
			
			try {
				//解析返回的XML
				Document doc=DocumentHelper.parseText(str);
				//获取根节点
				Element rootElt=doc.getRootElement();
				// 获取根节点下的子节点的值
				String returnstatus=rootElt.elementText("returnstatus").trim();
				String message=rootElt.elementText("message").trim();
				String remainpoint=rootElt.elementText("remainpoint").trim();
				String taskID=rootElt.elementText("taskID").trim();
				String successCounts=rootElt.elementText("successCounts").trim();
				if("Success".equals(returnstatus)){
					log.info("短信发送成功！发送结果返回值为：" + returnstatus+";");
				}else{
					fret = 1;
					log.info("短信发送失败！ 发送结果返回值为：" + returnstatus+",失败号码"+";");
				}
			} catch (Exception e) {
				fret = 1;
				e.printStackTrace();
				System.out.println(e);
			}
		} catch (Exception e) {
			fret = 1;
			e.printStackTrace();
			return fret;
		} 
		return fret;		
	}
	
	/**
	 * 功能:发送短信 返回是否成功（三小时内只能发送3个）
	 * @author lijian
	 * @since 2016-12-29
	 * @param mobileNumber 电话号码（多个）
	 * @param templateName 模板名称
	 * @param parameter    模板参数
	 * @param jobTime      定时发送时间（可以为空 null）
	 * @return
	 */
	public static int sendSmsJson(String[] mobileNumber, String templateName, Map<String, String> parameter,Date jobTime){
		ResourceBundle smsconfig = PropertyResourceBundle.getBundle("smsconfig");
		String templateContent = smsconfig.getString(templateName);
		String smsContent = replaceParameter(templateContent, parameter);
		smsContent=smsContent+smsconfig.getString("orgName");//内容+【签名】
		System.out.println("::::smsContent=" + smsContent);
		int fret = 0;// 成功
		try {
			String mobiles = "";
			if(mobileNumber==null){
				return 1; // 成功 参数为空
			}
			for(String mobile : mobileNumber){
				log.info("手机号码："+mobile);
				if(StringUtils.isEmpty(mobiles)){
					mobiles+=mobile;
				}else{
					mobiles+=mobile+",";
				}
			}
			System.out.println("user_id=" + smsconfig.getString("user_id"));
			System.out.println("login_id=" + smsconfig.getString("login_id"));
			System.out.println("login_password=" + smsconfig.getString("login_password"));
			HttpClient client=new HttpClient();				
			PostMethod post=new PostMethod(SMS_SEND_UTF8_URL);
			post.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
			NameValuePair userid=new NameValuePair("userid",smsconfig.getString("user_id"));
			NameValuePair account=new NameValuePair("account",smsconfig.getString("login_id"));
			NameValuePair password=new NameValuePair("password",smsconfig.getString("login_password"));
			NameValuePair mobile=new NameValuePair("mobile",mobiles);
			NameValuePair content=new NameValuePair("content",new String(smsContent.getBytes("utf-8"),"utf-8"));
			NameValuePair sendTime=new NameValuePair("sendTime","");
			if(jobTime!=null){
				String sendTimeString = DateUtils.getFormatDateTime(jobTime,DateUtils.PARSE_PATTERNS[1]);
				sendTime=new NameValuePair("sendTime",sendTimeString);
			}
			NameValuePair extno=new NameValuePair("extno","");
			post.setRequestBody(new NameValuePair[]{userid,account,password,mobile,content,sendTime,extno});
			int statu=client.executeMethod(post);
			System.out.println("statu="+statu);
			String str=post.getResponseBodyAsString();
			System.out.println(str);			
			
			try {
				//解析返回的XML
				Document doc=DocumentHelper.parseText(str);
				//获取根节点
				Element rootElt=doc.getRootElement();
				// 获取根节点下的子节点的值
				String returnstatus=rootElt.elementText("returnstatus").trim();
				String message=rootElt.elementText("message").trim();
				String remainpoint=rootElt.elementText("remainpoint").trim();
				String taskID=rootElt.elementText("taskID").trim();
				String successCounts=rootElt.elementText("successCounts").trim();
				if("Success".equals(returnstatus)){
					log.info("短信发送成功！发送结果返回值为：" + returnstatus+";");
				}else{
					fret = 1;
					log.info("短信发送失败！ 发送结果返回值为：" + returnstatus+",失败号码"+";");
				}
			} catch (Exception e) {
				fret = 1;
				e.printStackTrace();
				System.out.println(e);
			}
		} catch (Exception e) {
			fret = 1;
			e.printStackTrace();
			return fret;
		} 
		return fret;		
	}

	public static String replaceParameter(String templateContent, Map<String, String> parameter){
		if (parameter == null) {
			return templateContent;
		}
		for (String key : parameter.keySet()) {
			templateContent = templateContent.replace("{" + key + "}", parameter.get(key));
		}
		return templateContent;
	}

	
}
